package day3.datasource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

import javax.sql.DataSource;

public class MyConnetionHandler implements InvocationHandler {
	private Connection realConnection;
	private Connection warpedConnection;
	private MyDataSource2 dataSource;

	private int maxUsedCount = 5;
	private int currentUsedCount = 0;
	
	MyConnetionHandler(MyDataSource2 dataSource){
		this.dataSource=dataSource;
	}
	
	
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		if(method.getName().equals("close")){
			currentUsedCount++;
			dataSource.reduceCurrent();
			if(currentUsedCount>=maxUsedCount){
				
				realConnection.close();
			}else {
				dataSource.back2Pool(warpedConnection);
			}
			return null;
		}
		return method.invoke(realConnection, args);
	}



	public Connection bind(Connection connection) {
		// TODO Auto-generated method stub
		realConnection=connection;
		warpedConnection=(Connection) Proxy.newProxyInstance(
				this.getClass().getClassLoader(), 
				new Class[] { Connection.class },
				this);
		return warpedConnection;
	}

}
